package com.yanqu.road.server.cmd.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.logic.cross.CrossRankListModel;
import com.yanqu.road.logic.pb.CrossRankPb;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.activity.ActivityRankMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.LinkedList;

@Cmd(code = Protocol.C_CROSS_ACTIVITY_SERVER_QUERY_RANK, desc = "跨服活动区服查询排行榜")
public class CrossActivityQueryRankListCmd extends CrossCommand {
    private int activityId;
    private long queryServerId;
    private long userId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossActivityProto.CrossActivityQueryRankListReqMsg reqMsg = CrossActivityProto.CrossActivityQueryRankListReqMsg.parseFrom(packet.getBytes());
        activityId = reqMsg.getActivityId();
        queryServerId = reqMsg.getServerId();
        userId = packet.getPlayerId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        CrossRankListModel crossRankListModel = ActivityRankMgr.getCrossRankListModel(queryServerId, activityId);
        CrossActivityProto.CrossActivityQueryRankListRespMsg.Builder respMsg = CrossActivityProto.CrossActivityQueryRankListRespMsg.newBuilder();
        respMsg.setActivityId(activityId);
        if(null != crossRankListModel){
            ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
            int maxRank = 0;
            if(null != activityInfo) {
                maxRank = Integer.parseInt(activityInfo.getParam6());
            }
            LinkedList<CrossUserRank> dataList = crossRankListModel.getRankList();
            if(maxRank > 0){
                while (dataList.size() > maxRank){
                    dataList.removeLast();
                }
            }
            respMsg.setRankList(CrossRankPb.parseRankListMsg(dataList));
        }else {
            respMsg.setRankList(RankProto.RankListMsg.newBuilder());
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ACTIVITY_SERVER_QUERY_RANK_LIST_NOTIFY, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    @Override
    public void sendData() {

    }
}
